package com.xiaobias;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.*;

public class PasswordGeneratorSegment {
    // 定义字符集：大小写字母、数字和符号
    private static final String CHARACTERS =
            "abcdefghijklmnopqrstuvwxyz" +  // 小写字母
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +  // 大写字母
                    "0123456789" +                  // 数字
                    "!@#$%^&*()-_=+[]{}|;:,.<>?";   // 符号

    private static final int MAX_LENGTH = 32; // 最大密码长度
    private static final int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors(); // 线程池大小

    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        // 生成1到32位的所有密码组合
        for (int length = 1; length <= MAX_LENGTH; length++) {
            // 将字符集分片，每个线程负责一部分
            int segmentSize = CHARACTERS.length() / THREAD_POOL_SIZE;
            for (int i = 0; i < THREAD_POOL_SIZE; i++) {
                int start = i * segmentSize;
                int end = (i == THREAD_POOL_SIZE - 1) ? CHARACTERS.length() : start + segmentSize;
                String segment = CHARACTERS.substring(start, end);

                // 提交任务到线程池
                executor.submit(new PasswordGeneratorTask(length, segment));
            }
        }

        // 关闭线程池
        executor.shutdown();
        try {
            // 等待所有任务完成
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 密码生成任务
     */
    private static class PasswordGeneratorTask implements Runnable {
        private final int length; // 密码长度
        private final String segment; // 字符集分片

        public PasswordGeneratorTask(int length, String segment) {
            this.length = length;
            this.segment = segment;
        }

        @Override
        public void run() {
            String fileName = "passwords_length_" + length + "_segment_" + segment.hashCode() + ".txt";
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
                System.out.println("Generating passwords of length: " + length + " with segment: " + segment);
                generatePasswordsRecursive("", length, segment, writer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 递归生成密码组合
         */
        private void generatePasswordsRecursive(String current, int length, String segment, BufferedWriter writer) throws IOException {
            if (current.length() == length) {
                writer.write(current + "\n");
                return;
            }

            // 只使用当前分片的字符集
            for (char c : segment.toCharArray()) {
                generatePasswordsRecursive(current + c, length, CHARACTERS, writer);
            }
        }
    }
}
